<?php 

namespace app\common;

require_once __DIR__.'/Base.php';
use app\common\Base;


/**
 * 路由类
 */
class Rule extends Base
{
	
	function __construct()
	{
        parent::__construct(); 
	}
    

	/**
     * 路由入口
     */
    public function entrance($message)
    {   
        //添加记录
        $this->log('收到用户收据：');
        $this->log($message);
        if(in_array($message,array('{"type":"pong"}','{"type":"ping"}'))){
            return;
        }
        if(is_null($message)){
            return;
        }
        if(is_null(json_decode($message))){
            return $this->outMessage(9999,"API messages are not legitimate JSON formats!".$message,[]);
        }
        $msg = json_decode($message,true);
        if(!isset($msg['api'])){
            return $this->outMessage(9998,'unknow error!',[]);
        }
        //对进来的端口进行判断
        //来自pc的消息     
        if($_SESSION['app_type'] == 'pda' || $_SESSION['app_type'] == 'pc'){
            $api = $msg['api'];
            $arr_api = explode('_',$api);
            $module = $arr_api[1];
            $class_name = ucfirst($arr_api[2]);

            // 判断文件路径是否存在
            $dir = PATH.'controller/'.$module;
            if(!is_dir($dir)){
                return $this->outMessage(9996,'method not find!');
            }

            // 判断文件是否存在
            $php_field = PATH.'controller/'.$module.'/'.$class_name.'.php';
            if(!file_exists($php_field)){
                return $this->outMessage(9996,'method not find!');
            }
            
            //将要调用的文件引入进来
            include_once PATH.'controller/'.$module.'/'.$class_name.'.php';
            try {
                $className = 'app\controller\\'.$module.'\\'.$class_name;
                $obj = new $className();
                if(method_exists($obj,$api)){ 
                    $obj->save_api($api);
                    $log[] = '调用了接口';
                    $log[] = $api;
                    $this->log($log,'debug');
                    //根据api 名称动态路由调用函数
                    $obj->$api($msg); 
                }else{
                    return $this->outMessage(9996,'method not find!');
                }
            } catch (Exception $e) {
                echo $e->getMessage();
                return $this->outMessage(9996,'method not find!',[],'error');
            }    
        }
        return;
    }







}






